package com.chen.pfm.slice;

import com.chen.pfm.LoginAbility;
import com.chen.pfm.MainAbility;
import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.entity.User;
import com.chen.pfm.utils.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;

public class ChangePasswordSlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "ChangePasswordSlice");
    int uid;
    User user;
    TextField oldPassword;
    String old;
    TextField newPassword;
    TextField reNewPassword;
    Button confirm_btn;
    int logout;

    @Override
    protected void onStart(Intent intent) {

        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_change_password);
        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener((component) -> {
            terminate();
        });
        String uid = DataBaseUtil.GetValue(this, "uid");
        if (uid == null) {
            MyToast.showMyToast(this, "用户uid为空");
            return;
        }
        user = UserDBUtil.queryOneByUid(this, Integer.valueOf(uid));

        findComponentById(ResourceTable.Id_confirm_btn).setClickedListener((component) -> {
            oldPassword = (TextField) findComponentById(ResourceTable.Id_oldPassword);
            reNewPassword = (TextField) findComponentById(ResourceTable.Id_reNewPassword);
            newPassword = (TextField) findComponentById(ResourceTable.Id_newPassword);
            if (oldPassword.getText() == null || "".equals(oldPassword.getText())) {
                MyToast.showMyToast(this, "原密码不能为空");
                return;
            } else if (newPassword.getText() == null || "".equals(newPassword.getText())) {
                MyToast.showMyToast(this, "新密码不能为空");
                return;
            } else if (reNewPassword.getText() == null || "".equals(reNewPassword.getText())) {
                MyToast.showMyToast(this, "再次新密码不能为空");
                return;
            } else if (!newPassword.getText().equals(reNewPassword.getText())) {
                MyToast.showMyToast(this, "两次新密码不一致");
                return;
            } else {
                old = user.getPassword();
                if (old == null) {
                    HiLog.error(LABEL, "原密码居然没在本地数据库里....");
                    return;
                } else if (!oldPassword.getText().equals(old)) {
                    MyToast.showMyToast(this, "原密码输入错误！");
                    return;
                } else {
                    //修改密码，发送请求
                    HiLog.info(LABEL, "启动线程去更新远端的数据！");
                    //那么从远端数据库同步，同步完成再加载

                    try {
                        int delete = UserDBUtil.delete(this, user);
                        if (delete > 0) {
                            updateRemoteData(MyUtil.updatePasswordByUid, null);

                        } else {
                            return;
                        }
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }

                }
            }

        });//点击事件结束


    }//onstaer结束

    private void updateRemoteData(String url, Object sendJsonObject) {
        //1.启动一个线程去得到数据
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            ResultVo resultVo;
            String getRequestjson = null;
            Gson gson = new Gson();
            RequestBody requestBody = new FormBody.Builder()
                    .add("uid", String.valueOf(user.getUid()))
                    .add("password", reNewPassword.getText())
                    .build();
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, requestBody);
            } catch (IOException e) {
                e.printStackTrace();
            }
            HiLog.info(LABEL, "网络返回情况: " + (getRequestjson == null));
            if (getRequestjson == null) {
                HiLog.info(LABEL, "无法连接到网络！");
                //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                getUITaskDispatcher().asyncDispatch(() -> {
                            //在这里执行页面ui组件的显示刷新
                            MyToast.showMyToast(this, "无法连接到网络");
                        }
                );
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }
                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });

                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                        if (resultVo.getCode() == 200) {
                            logout();
                        }

                    });
                }

            }

        });//线程结束

    }


    void logout() {
        getUITaskDispatcher().asyncDispatch(() -> {
            MyToast.showMyToast(getContext(), "数据已更新,正为你跳转登录页面...");
        });
        //删除token,退出登录
        DataBaseUtil.deleteValue(this, "token");
        DataBaseUtil.deleteValue(this, "uid");
        terminate();
    }

}
